//
//  UserAccessToken.swift
//  App
//
//  Created by 汤泽川 on 2019/3/28.
//

import Foundation
import Vapor
import FluentMySQL

struct UserAccessToken : BaseModel {
    var createdAt: Date?
    var updatedAt: Date?
    var id : Int?
    var username : String
    var accessToken : String
    init(username : String, accessToken : String) {
        self.username = username
        self.accessToken = accessToken
    }
}

extension UserAccessToken {
    static public func createTokenWithUsername(username : String) -> UserAccessToken {
        let digestStr = username + String(TimeManager.currentDate())
        let accessToken = digestStr.sha1
        let userToken = UserAccessToken(username: username, accessToken: accessToken)
        return userToken
    }
    
    static public func queryUserInfo(accessToken : String, req : Request) throws -> Future<UserInfo> {
        return UserAccessToken.query(on: req).filter(\.accessToken == accessToken).first().flatMap {
            tokenInfo in
            guard let tokenInfo = tokenInfo else {
                throw APIError.illegalAccessTokenError
            }
            return UserInfo.query(on: req).filter(\.username == tokenInfo.username).first().map {
                userInfo in
                guard let userInfo = userInfo else {
                    throw APIError.userDoesNotExistError
                }
                return userInfo
            }
        }
    }
}
